package com.tigercel.xiangchengyun.ui.activities

import android.annotation.SuppressLint
import android.app.Activity
import android.content.*
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.support.v4.content.ContextCompat
import android.view.View
import android.webkit.*
import android.widget.SeekBar
import cn.sharesdk.framework.Platform
import cn.sharesdk.framework.PlatformActionListener
import cn.sharesdk.framework.ShareSDK
import cn.sharesdk.tencent.qq.QQ
import cn.sharesdk.wechat.friends.Wechat
import cn.sharesdk.wechat.moments.WechatMoments
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.tigercel.xiangchengyun.R
import com.tigercel.xiangchengyun.ui.BaseActivity
import com.tigercel.xiangchengyun.utils.Global
import com.tigercel.xiangchengyun.utils.JsonUtil
import com.tigercel.xiangchengyun.utils.PreferencesUtil
import kotlinx.android.synthetic.main.activity_web_view.*
import kotlinx.android.synthetic.main.include_titlebar.*
import me.curzbin.library.BottomDialog
import org.jetbrains.anko.toast


class WebViewActivity : BaseActivity() {
    override val mContentLayoutResouredId: Int = R.layout.activity_web_view
    lateinit var cmb: ClipboardManager
    private var localDatas: PreferencesUtil? = null
    private var id = ""
    private var model = ""
    private var is_collect = ""
    private var comment_num = ""
    override fun initViews() {
        sb_lightness.progress = getBrightness(this)
        sb_lightness.max = 255
        localDatas = PreferencesUtil(this)
        id = intent.getStringExtra("id")
        model = intent.getStringExtra("model")
        if (id == "") {
            li_comment.visibility = View.GONE
        }
        action()
        cmb = this.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        cmb.primaryClip = ClipData.newPlainText(null, intent.getStringExtra("url"))
        titlebar_tv.text = intent.getStringExtra("title")
        titlebar_iv_left.setImageDrawable(resources.getDrawable(R.drawable.btn_nav_back))
        titlebar_iv_left.visibility = View.VISIBLE
        titlebar_iv_left.setOnClickListener(View.OnClickListener { this.finish() })
        titlebar_iv_right.setImageResource(R.drawable.btn_nav_share)
        titlebar_iv_right.visibility = View.VISIBLE
        titlebar_iv_right.setOnClickListener {
            val bottomDialog = BottomDialog(this)
            bottomDialog.orientation(BottomDialog.VERTICAL)
            bottomDialog.layout(BottomDialog.GRID)
            if (is_collect=="1"){
                bottomDialog.inflateMenu(R.menu.menu_grid1, {
                    when (it.title) {
                        "微信好友" -> showShare(Wechat.NAME)
                        "微信朋友圈" -> showShare(WechatMoments.NAME)
                        "QQ好友" -> showShare(QQ.NAME)
                        "复制链接" -> if (cmb.hasPrimaryClip()) {
                            cmb.primaryClip.getItemAt(0).text
                            bottomDialog.dismiss()
                            toast("链接复制成功")
                        }
                        "刷新" -> {
                            webView.reload()
                            bottomDialog.dismiss()
                        }
                        "收藏" -> if (localDatas!!.preferences["isAlreadyLogin"] == "true") {
                            collection()
                            it.icon = ContextCompat.getDrawable(this, R.drawable.btn_share_collect)
                        } else {
                            val intent = Intent()
                            intent.setClass(this, LoginActivity::class.java)
                            startActivity(intent)
                        }
                        "调整亮度" -> {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                // 判断是否有WRITE_SETTINGS权限if(!Settings.System.canWrite(this))
                                if (!Settings.System.canWrite(this)) {
                                    val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
                                            Uri.parse("package:$packageName"))
                                    startActivityForResult(intent, 1)
                                } else {
                                    li_change_lightness.visibility = View.VISIBLE
                                    processShow()
                                    bottomDialog.dismiss()
                                }

                            }
//
                        }
                    }
                })
            }else{
                bottomDialog.inflateMenu(R.menu.menu_grid, {
                    when (it.title) {
                        "微信好友" -> showShare(Wechat.NAME)
                        "微信朋友圈" -> showShare(WechatMoments.NAME)
                        "QQ好友" -> showShare(QQ.NAME)
                        "复制链接" -> if (cmb.hasPrimaryClip()) {
                            cmb.primaryClip.getItemAt(0).text
                            bottomDialog.dismiss()
                            toast("链接复制成功")
                        }
                        "刷新" -> {
                            webView.reload()
                            bottomDialog.dismiss()
                        }
                        "收藏" -> if (localDatas!!.preferences["isAlreadyLogin"] == "true") {
                            collection()
                            it.icon = ContextCompat.getDrawable(this, R.drawable.btn_share_collect)
                        } else {
                            val intent = Intent()
                            intent.setClass(this, LoginActivity::class.java)
                            startActivity(intent)
                        }
                        "调整亮度" -> {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                // 判断是否有WRITE_SETTINGS权限if(!Settings.System.canWrite(this))
                                if (!Settings.System.canWrite(this)) {
                                    val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
                                            Uri.parse("package:$packageName"))
                                    startActivityForResult(intent, 1)
                                } else {
                                    li_change_lightness.visibility = View.VISIBLE
                                    processShow()
                                    bottomDialog.dismiss()
                                }

                            }
//
                        }
                    }
                })
            }


            bottomDialog.show()
            tv_ensure_light.setOnClickListener { li_change_lightness.visibility = View.GONE }
        }
        if (intent.getStringExtra("url") == "") {
            webView.visibility = View.GONE
            progressbar.visibility = View.GONE
        } else {
            initWebViewSettings()
            webView.webViewClient = MyWebViewClient()
            webView.webChromeClient = MyWebChromeClient()
            progressbar.max = 100
            webView.loadUrl(intent.getStringExtra("url"))
        }

    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebViewSettings() {
        val settings = webView.settings
        settings.setAppCacheEnabled(true)
        settings.blockNetworkImage = false
        settings.builtInZoomControls = false
        settings.setSupportZoom(true)
        settings.javaScriptEnabled = true
        settings.domStorageEnabled = true
        settings.cacheMode = WebSettings.LOAD_NO_CACHE
        //屏蔽长按事件，禁止在web页面中选择文本
        webView.setOnLongClickListener({ true })
    }

    //WebViewClient就是帮助WebView处理各种通知、请求事件的。
    internal inner class MyWebViewClient : WebViewClient() {
        @SuppressLint("NewApi")
        override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
            view.loadUrl(request.url.toString())
            return true
        }

        //        shouldOverrideUrlLoading(WebView view, String url)  最常用的，比如上面的。
        //        //在网页上的所有加载都经过这个方法,这个函数我们可以做很多操作。
        //        //比如获取url，查看url.contains(“add”)，进行添加操作
        //
        //        shouldOverrideKeyEvent(WebView view, KeyEvent event)
        //        //重写此方法才能够处理在浏览器中的按键事件。
        //
        //        onPageStarted(WebView view, String url, Bitmap favicon)
        //        //这个事件就是开始载入页面调用的，我们可以设定一个loading的页面，告诉用户程序在等待网络响应。
        //
        //        onPageFinished(WebView view, String url)
        //        //在页面加载结束时调用。同样道理，我们可以关闭loading 条，切换程序动作。
        //
        //        onLoadResource(WebView view, String url)
        //        // 在加载页面资源时会调用，每一个资源（比如图片）的加载都会调用一次。
        //
        //        onReceivedError(WebView view, int errorCode, String description, String failingUrl)
        //        // (报告错误信息)
        //
        //        doUpdateVisitedHistory(WebView view, String url, boolean isReload)
        //        //(更新历史记录)
        //
        //        onFormResubmission(WebView view, Message dontResend, Message resend)
        //        //(应用程序重新请求网页数据)
        //
        //        onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host,String realm)
        //        //（获取返回信息授权请求）
        //
        //        onReceivedSslError(WebView view, SslErrorHandler handler, SslError error)
        //        //重写此方法可以让webview处理https请求。
        //
        //        onScaleChanged(WebView view, float oldScale, float newScale)
        //        // (WebView发生改变时调用)
        //
        //        onUnhandledKeyEvent(WebView view, KeyEvent event)
        //        //（Key事件未被加载时调用）
    }

    //WebChromeClient是辅助WebView处理Javascript的对话框，网站图标，网站title，加载进度等
    internal inner class MyWebChromeClient : WebChromeClient() {
        override fun onProgressChanged(view: WebView, newProgress: Int) {
            progressbar.progress = newProgress
            if (newProgress == 100) {
                progressbar.visibility = View.GONE
            } else {
                progressbar.visibility = View.VISIBLE
            }
        }
        //        //获取Web页中的title用来设置自己界面中的title
        //        //当加载出错的时候，比如无网络，这时onReceiveTitle中获取的标题为 找不到该网页,
        //        //因此建议当触发onReceiveError时，不要使用获取到的title
        //        @Override
        //        public void onReceivedTitle(WebView view, String title) {
        //            MainActivity.this.setTitle(title);
        //        }
        //
        //        @Override
        //        public void onReceivedIcon(WebView view, Bitmap icon) {
        //            //
        //        }
        //
        //        @Override
        //        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
        //            //
        //            return true;
        //        }
        //
        //        @Override
        //        public void onCloseWindow(WebView window) {
        //        }
        //
        //        //处理alert弹出框，html 弹框的一种方式
        //        @Override
        //        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        //            //
        //            return true;
        //        }
        //
        //        //处理confirm弹出框
        //        @Override
        //        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult
        //                result) {
        //            //
        //            return true;
        //        }
        //
        //        //处理prompt弹出框
        //        @Override
        //        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
        //            //
        //            return true;
        //        }
    }

    private fun showShare(platformName: String) {
        val sp = Platform.ShareParams()
        sp.title = intent.getStringExtra("title")
//        sp.titleUrl = "http://sharesdk.cn" // 标题的超链接
//        sp.text = "测试分享的文本"
//        sp.imageUrl = "http://www.someserver.com/测试图片网络地址.jpg"
//        sp.site = "发布分享的网站名称"
        sp.siteUrl = intent.getStringExtra("url")
        val platform = ShareSDK.getPlatform(platformName)
        // 设置分享事件回调（注：回调放在不能保证在主线程调用，不可以在里面直接处理UI操作）
        platform.platformActionListener = object : PlatformActionListener {
            override fun onComplete(p0: Platform?, p1: Int, p2: HashMap<String, Any>?) {
            }

            override fun onError(arg0: Platform, arg1: Int, arg2: Throwable) {
                //失败的回调，arg:平台对象，arg1:表示当前的动作，arg2:异常信息
            }

            override fun onCancel(arg0: Platform, arg1: Int) {
                //取消分享的回调
            }
        }
        // 执行图文分享
        platform.share(sp)

    }

    private fun processShow() {
        sb_lightness.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                setScreenBrightness(seekBar.progress)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}

            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })
    }

    /**
     * 设置屏幕的亮度
     */
    private fun setScreenBrightness(process: Int) {

        //设置当前窗口的亮度值.这种方法需要权限android.permission.WRITE_EXTERNAL_STORAGE
        val localLayoutParams = window.attributes
        val f = process / 255.0f
        localLayoutParams.screenBrightness = f
        window.attributes = localLayoutParams
        //修改系统的亮度值,以至于退出应用程序亮度保持
        saveBrightness(contentResolver, process)

    }

    fun saveBrightness(resolver: ContentResolver, brightness: Int) {
        //改变系统的亮度值(申请权限失败)
        //这里需要权限android.permission.WRITE_SETTINGS
        //设置为手动调节模式
        Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL)
        //保存到系统中
        val uri = android.provider.Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS)
        android.provider.Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, brightness)
        resolver.notifyChange(uri, null)
    }

    fun getBrightness(activity: Activity): Int {
        var brightValue = 0
        val contentResolver = activity.getContentResolver()
        try {
            brightValue = Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS)
        } catch (e: Settings.SettingNotFoundException) {
            e.printStackTrace()
        }

        return brightValue
    }

    private fun collection() {
        val token = localDatas!!.preferences["token"]
        OkGo.post<String>(Global.baseUrl + Global.collection)
                .tag(this)
                .params("token", token)
                .params("content_id", id)
                .params("model", model)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val result = response!!.body()
                        val status = JsonUtil.get_key_string("status", result)
                        val msg = JsonUtil.get_key_string("msg", result)
                        val code = JsonUtil.get_key_string("code", result)
                        val data = JsonUtil.get_key_string("data", result)
                        if (status == "0") {
                            toast("收藏成功")
                        }
                    }

                })
    }

    private fun action() {
        val token = localDatas!!.preferences["token"]
        OkGo.post<String>(Global.baseUrl + Global.action)
                .tag(this)
                .params("token", token)
                .params("content_id", id)
                .params("model", model)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val result = response!!.body()
                        val status = JsonUtil.get_key_string("status", result)
                        val msg = JsonUtil.get_key_string("msg", result)
                        val code = JsonUtil.get_key_string("code", result)
                        val data = JsonUtil.get_key_string("data", result)
                        if (status == "0") {
                            is_collect = JsonUtil.get_key_string("is_collect",data)
                            comment_num = JsonUtil.get_key_string("comment_num",data)
                        }
                    }

                })
    }
}
